// 离线获取经纬度
function getunLatlng() {
  return new Promise((resolve, reject) => {
    console.log('gps')
    // #ifdef APP-PLUS
    plus.geolocation.getCurrentPosition(function(p) {
		  console.log(p, 'position==')
		  resolve({
		    lat: p.coords.latitude,
		    lng: p.coords.longitude
		  })
		  //根据坐标获取位置
    }, function(e) {
		  console.log(e, 'e==失败')
      reject('获取失败')
    }, {
		  coordsType: 'wgs84'
    })
    // #endif
  })
}

// 在线获取经纬度
function getolLatlng () {
  return new Promise((resolve, reject) => {
    uni.getLocation({
      type: 'wgs84',
      success: res => {
        resolve({
          lat: res.latitude,
          lng: res.longitude
        })
      },
      fail: err => {
        console.log(err)
        reject('获取失败')
      }
    })
  })
}

// 获取当前是否有网
function getNetwork () {
  return new Promise((resolve, reject) => {
    uni.getNetworkType({
		  success: res => {
		    console.log(res.networkType) //网络类型 wifi、2g、3g、4g、ethernet、unknown、none
		    if (res.networkType === 'none') {
		      console.log('当前无网络', res.networkType)
		      getunLatlng().then(res => {
            resolve(res)
          }).catch((err) => {
            reject(err)
          })
		    } else {
		      console.log('有网络', res.networkType)
          getolLatlng().then(res => {
            resolve(res)
          }).catch((err) => {
            reject(err)
          })
		    }
		  }
    })
  })

}
// 获取权限
export function permLocation() {
  return new Promise((resolve, reject) => {
    uni.getSystemInfo({
		  success: res => {
        console.log('获取权限', res)
		    var platform = res.platform
		    if (platform === 'android') {
		      console.log('android')
		      var context = plus.android.importClass('android.content.Context')
		      var locationManager = plus.android.importClass('android.location.LocationManager')
		      var main = plus.android.runtimeMainActivity()
		      var mainSvr = main.getSystemService(context.LOCATION_SERVICE)
		      if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
		        uni.showModal({
		          title: '提示',
		          content: '请先开打开定位服务功能',
		          showCancel: false
		        })
            reject()
		      } else {
		        console.log('GPS已经开启')
		        resolve()
		      }
		    } else if (system.platform === 'ios') {
		      console.log('ios')
          resolve()
		    }
		  }
    })
  })
}
export async function useLocation() {
  return getNetwork()
}